<script setup lang="ts">
/**
 * 表格组件,数据展示,分页
 */
import {getCurrentInstance, onMounted, ref} from "vue";
import {crudTableProps} from "@/components/crud/table/Props";
import {deleteEntry} from "@/api/strapi";
// 引入图标
import { Refresh, Grid } from "@element-plus/icons-vue";
import {FilterCondition} from "@/components/crud/types";
import CrudFilter from "@/components/crud/filter/CrudFilter.vue";
import {openCreateDialog, openUpdateDialog} from "@/components/crud/form/FormDialog";
import {ElMessage, ElMessageBox} from "element-plus";
import {openDialog} from "@/utils/DialogUtils";
import CrudDetail from "@/components/crud/detail/CrudDetail.vue";
import {ErrorUtils} from "@/utils/ErrorUtils";
import {useGetEntries} from "@/api/useStrapi";

const page = ref(1) // 当前页码，从 1 开始
const pageSize = ref<number>(parseInt(localStorage.getItem('pageSize') || '20', 10)) // 当前页大小

defineOptions({
  name: 'crud-table'
})
const props = defineProps({
  ...crudTableProps
});
const filters = ref<Array<FilterCondition>>([])
// 搜索条件
function search(o: FilterCondition[]) {
  filters.value = o
  initData()
}

const {data, fetch: getTableData, loading, total} = useGetEntries()

// 编辑
const handleEdit = (row: any) => {
  if (!props.url) return;
  if (!props.updateConfig) return;
  openUpdateDialog(context, props.url, '编辑', props.updateConfig, row.documentId, () => {
    initData()
  })
};

// 新增
function onCreateClick () {
  if (!props.url) return;
  if (!props.createConfig) return;
  openCreateDialog(context,props.url, '新增', props.createConfig, () => {
    initData()
  })
}

// 查看
const handleDetails = (row: any) => {
  if (context && props.detailOptions) {
    openDialog(context, CrudDetail, {value: row, options: props.detailOptions},{title: '详情'})
  }
};

const handleDelete = (row: any) => {
  // 弹出二次确认对话框
  ElMessageBox.confirm(
      '确定要删除该条目吗？此操作不可逆！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    if (!props.url) return;

    // 调用删除接口
    return deleteEntry(props.url, row.documentId);
  }).then(() => {
    ElMessage.success('删除成功',);
    // 刷新数据
    initData();
  }).catch((error) => {
    if (error === 'cancel') {
      // 用户点击取消，不做处理
      return;
    }
    ErrorUtils.handleError(error);
  });
};
// 刷新数据
const handleRefresh = () => {
  initData();
};
const context = getCurrentInstance()

// 列设置，这里先空实现，你可按需补充
const handleColumnSetting = () => {
  console.log('列设置操作');
};
// 初始化数据
function initData () {
  getTableData(
        props.url || '',
        page.value,
        pageSize.value,
        [...props.filters, ...filters.value], // 合并外部筛选
    )
}

// 页码改变时触发
const handleCurrentChange = (val: number) => {
  page.value = val;
  initData();
}

// 每页条数改变时触发
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  initData();
}
onMounted(() => {
  if (props.url) {
    initData();
  }
})
defineExpose({
  initData,
})
</script>

<template>
  <el-card>
    <crud-filter  v-if="props.filterOptions" :options="props.filterOptions" @change="search"/>

    <div style="display: flex;flex-direction: row;">
      <div style="flex: 1">
        <el-button type="primary" @click="onCreateClick">新增</el-button>
      </div>
      <!-- 操作栏 -->
      <div class="table-actions">
        <el-tooltip content="刷新" placement="top">
          <el-button @click="handleRefresh" :icon="Refresh" circle>
          </el-button>
        </el-tooltip>
        <el-popover title="列设置" placement="bottom">
          <template #reference>
            <el-button @click="handleColumnSetting" :icon="Grid" circle>
            </el-button>
          </template>
          <template #default>
            <div v-for="column in columns" :key="column.field">
              <el-checkbox v-model="column.enable">{{column.title}}</el-checkbox>
            </div>
          </template>
        </el-popover>
      </div>
    </div>

    <el-table
        :data="data"
        border
        :loading="loading"
        style="width: 100%">
      <!-- 用数据渲染列 -->
      <template v-if="columns">
        <template  v-for="column in columns">
          <el-table-column :label="column.title"
                           v-if="column.enable"
                           :width="column.width"
                           :align="column.align"
                           :show-overflow-tooltip="column.showOverflowTooltip"
                           :filterable="column.filterable">
            <template #default="{row}">
              <!-- 渲染列 -->
              <template v-if="column.enable">
                <component v-if="column.component" :is="column.component" :column="column" :value="row" />
                <span v-else>{{row[column.field]}}</span>
              </template>

            </template>
          </el-table-column>
        </template>

      </template>
      <el-table-column label="操作">
        <template #default="scope">
          <slot name="actions" :row="scope.row"></slot>
          <el-button v-if="props.hasEdit && updateConfig && updateConfig.length > 0" @click="handleEdit(scope.row)" size="small">编辑</el-button>
          <el-button v-if="props.hasDetail && detailOptions && detailOptions.length > 0" @click="handleDetails(scope.row)" size="small">详情</el-button>
          <el-button v-if="props.hasDelete" type="danger" @click="handleDelete(scope.row)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
      <!-- 分页组件 -->
      <el-pagination
          style="margin-top: 12px;justify-content: right;"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      />

  </el-card>

</template>

<style scoped>
.table-actions {
  margin-bottom: 12px;
  text-align: right;
}
</style>



